package com.question.business.org.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.question.business.org.entity.OrgDept;
import com.question.business.org.mapper.OrgDeptMapper;
import com.question.business.org.service.IOrgDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 机构部门服务实现类
 *
 * @author star
 * @since 2023-09-15
 */
@Slf4j
@Service
public class OrgDeptServiceImpl extends ServiceImpl<OrgDeptMapper, OrgDept> implements IOrgDeptService {

    /**
     * 机构部门查询
     *
     * @param orgId 机构ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryDeptByOrgId(String orgId) {
        return baseMapper.queryDeptByOrgId(orgId);
    }

    /**
     * 部门机构查询
     *
     * @param deptId 部门ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryOrgByDeptId(String deptId) {
        return baseMapper.queryOrgByDeptId(deptId);
    }

    /**
     * 机构部门新增数据
     *
     * @param orgId   机构ID
     * @param deptIds 部门ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrgDept(@NotNull String orgId, List<String> deptIds) {
        // 删除机构部门
        baseMapper.deleteByOrgId(orgId);
        handleBatchAdd(Collections.singletonList(orgId), deptIds);
    }

    /**
     * 批量保存
     *
     * @param orgIds  机构ID
     * @param deptIds 部门ID
     */
    private void handleBatchAdd(List<String> orgIds, List<String> deptIds) {
        if (CollectionUtils.isNotEmpty(orgIds) && CollectionUtils.isNotEmpty(deptIds)) {
            List<OrgDept> data = new ArrayList<>();
            for (String orgId : orgIds) {
                for (String deptId : deptIds) {
                    OrgDept entity = new OrgDept();
                    entity.setDeptId(deptId);
                    entity.setOrgId(orgId);
                    data.add(entity);
                }
            }
            super.saveBatch(data);
        }
    }

    /**
     * 部门机构新增数据
     *
     * @param deptId 部门ID
     * @param orgIds 机构ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addDeptOrg(@NotNull String deptId, List<String> orgIds) {
        // 删除部门机构
        baseMapper.deleteByDeptId(deptId);
        handleBatchAdd(orgIds, Collections.singletonList(deptId));
    }
}